import {
  commitStudentInfoPC, deleteStudent, getStudentInfo, getStudents,
} from '@/graphql/student';
import { TStudentsQuery } from '@/utils/types';
import { useMutation, useQuery } from '@apollo/client';
import { message } from 'antd';

export const useGetStudents = (pageNum = 1, pageSize = 8) => {
  const { data, loading, refetch } = useQuery<TStudentsQuery>(getStudents, {
    variables: {
      page: {
        pageNum,
        pageSize,
      },
    },
  });
  return {
    data: data?.getStudents.data,
    page: data?.getStudents.page,
    loading,
    refetch,
  };
};

export const useDeleteStudent = ():[delHandler:Function, loading:boolean] => {
  const [del, { loading }] = useMutation(deleteStudent);
  const delHandler = async (id:string, callback:() => void) => {
    const res = await del({
      variables: {
        id,
      },
    });
    if (res.data.deleteStudent.code === 200) {
      callback();
      message.success(res.data.deleteStudent.message);
      return;
    }
    message.error(res.data.deleteStudent.message);
  };
  return [delHandler, loading];
};

export const useGetStudentInfo = (id:string) => {
  const { data, loading } = useQuery(getStudentInfo, {
    skip: !id,
    variables: {
      id,
    },
  });
  return {
    data: data?.getStudentInfo.data,
    loading,
  };
};

export const useEditStudentInfo = ():[editHandler:Function, loading:boolean] => {
  const [edit, { loading }] = useMutation(commitStudentInfoPC);
  const editHandler = async (id:string, params:any, callback:()=> void) => {
    const res = await edit({
      variables: {
        id,
        params,
      },
    });
    if (res.data.commitStudentInfoPC.code === 200) {
      message.success(res.data.commitStudentInfoPC.message);
      callback();
      return;
    }
    message.error(res.data.commitStudentInfoPC.message);
  };
  return [
    editHandler,
    loading,
  ];
};
